from virtual_operator_service_base.utils.json_util import to_json, DEST_CLIENT


class Response:
    def __init__(self, code, msg, http_status_code=None, data=None, popup=None):
        self.code = code
        self.msg = msg
        self.data = data
        self.popup = popup
        self.http_status_code = http_status_code if http_status_code is not None else 200

    def result(self, data=None):
        return Response.format(
            self.code,
            self.msg,
            self.http_status_code,
            self.data if data is None else data,
            self.popup,
        )

    def format(code, msg, http_status_code=None, data=None, popup=None):
        res = {'code': code, 'msg': msg}
        if data is not None:
            res['data'] = data
        if popup is not None:
            res['popup'] = popup
        status_code = http_status_code if http_status_code else 200
        return to_json(res, dest=DEST_CLIENT), status_code, {
            "content-type": "application/json; charset=utf-8"
        }


SUCCESS = Response(200, 'success', 200)
FAIL = Response(1, 'fail')
FORBIDDEN = Response(2, 'forbidden')
SERVER_ERROR = Response(-1, 'server internal error', 500)
INVALID_TIMESTAMP = Response(-3, 'invalid timestamp', 413)
INVALID_PARAMETER = Response(1, 'invalid parameters', 400)
